package com.zb.zeus.common.security.service;

import com.zb.zeus.common.core.domain.R;
import com.zb.zeus.common.core.utils.SecurityUtils;
import com.zb.zeus.common.core.utils.ServletUtils;
import com.zb.zeus.common.core.utils.StringUtils;
import com.zb.zeus.system.api.RemoteUserService;
import com.zb.zeus.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * token验证处理
 *
 * @author zb.zeus
 */
@Component
public class TokenHolderService {

    @Autowired
    @Lazy
    private RemoteUserService remoteUserService;


    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUser() {
        return getLoginUser(ServletUtils.getRequest());
    }

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUser(HttpServletRequest request) {
        // 获取请求携带的令牌
        String token = SecurityUtils.getToken(request);
        if (StringUtils.isNotEmpty(token)) {
            R<LoginUser> userRet = remoteUserService.getTokenUserInfo(token);
            if (userRet.getCode() == R.SUCCESS) {
                return userRet.getData();
            }
        }
        return null;
    }
}